package com.example.tb_log.log;

import androidx.annotation.NonNull;
import android.util.Log;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * TbLog的管理类，进行一些初始化
 */
public class TbLogManager {
    private static final String TAG = "TbLogManager";
    private TbLogConfig config;
    private static TbLogManager instance;
    private List<TbLogPrinter> printers = new ArrayList<>();

    private TbLogManager(TbLogConfig config, TbLogPrinter[] printers){
        this.config = config;
        if(printers.length == 0){
            this.printers.add(new TbConsolePrinter());
        }else{
            this.printers.addAll(Arrays.asList(printers));
        }

        if (config.enableCrashHandler()) {
            try {
                TbCrashHandler.getInstance().init(config.getContext(), config.getCrashLogPath());
                Log.i(TAG, "崩溃处理器已初始化");
            } catch (Exception e) {
                Log.e(TAG, "初始化崩溃处理器失败", e);
            }
        }
    }

    public static TbLogManager getInstance() {
        if (instance == null) {
            throw new IllegalStateException("TbLogManager 未初始化，请先调用 init() 方法");
        }
        return instance;
    }

    public static void init(@NonNull TbLogConfig config, TbLogPrinter... printers) {
        if (instance != null) {
            Log.w(TAG, "TbLogManager 已经初始化，请勿重复初始化");
            return;
        }
        instance = new TbLogManager(config, printers);
    }

    public TbLogConfig getConfig() {
        if (config == null) {
            throw new IllegalStateException("TbLogConfig 未初始化");
        }
        return config;
    }

    public List<TbLogPrinter> getPrinters() {
        return printers;
    }

    public void addPrinter(TbLogPrinter printer) {
        if (printer != null) {
            printers.add(printer);
        }
    }

    public void removePrinter(TbLogPrinter printer) {
        if (printers != null && printer != null) {
            printers.remove(printer);
        }
    }
}
